import {reqShopCart, reqDeleteCart, reqUpdateChecked} from '@/api/index.js';
import {SET_USERID} from "@/utils/USER_ID";

// 材料：
let state = {
    shopCartInfo: [],
    USER_ID: SET_USERID(),
};

// 加工：
let getters = {
    cartInfo(state) {
        return state.shopCartInfo[0] || {};
    }
};

// 厨师：
let mutations = {
    GETSHOPCART(state, payload) {
        state.shopCartInfo = payload;
    }
};

// 迎宾：
let actions = {
    async getShopCart({commit, state, dispatch}) {
        console.log(200);
        let result = await reqShopCart();
        console.log(result.data);
        console.log(201);
        if (result.code === 200) {
            commit('GETSHOPCART', result.data);
        }
    },
    async deleteCartById({commit, state, dispatch}, skuId) {
        let result = await reqDeleteCart(skuId);
        if (result.code === 200) {
            return result;
        } else {
            return Promise.reject();
        }
    },
    async changeChecked({commit, state, dispatch}, {skuId, isChecked}) {
        console.log(`SkuID: ${skuId}, isCheckedStatus: ${isChecked}`);
        let result = await reqUpdateChecked(skuId, isChecked);
        console.log(result);
        if (result.code === 200) {
            return result;
        } else {
            return Promise.reject();
        }

    },
    allUpdateChecked({commit, state, dispatch}, isChecked) {
        let arr = [];
        state.shopCartInfo[0].cartInfoList.forEach(item => {
            let ps = dispatch("changeChecked", {skuId: item.skuId, isChecked});
            arr.push(ps);
        })
        return Promise.all(arr);
    },
    deleteAllCart({commit, state, dispatch}) {
        let arr = [];
        state.shopCartInfo[0].cartInfoList.forEach(item => {
            if (item.isChecked === 1) {
                let ps = dispatch('deleteCartById', item.skuId);
                arr.push(ps);
            }
        })
        return Promise.all(arr);
    }
};

// 对外暴露
export default {
    state,
    mutations,
    actions,
    getters
};



